package com.quectel.emp.controller.workorder;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.func.LambdaUtil;
import com.quectel.base.tuple.Tuples;
import com.quectel.business.common.CommonBusiness;
import com.quectel.business.common.dept.DeptPersonMsgBusiness;
import com.quectel.business.common.util.sys.SysCodeUtils;
import com.quectel.business.common.workorder.WorkOrderBusiness;
import com.quectel.constant.PushConstants;
import com.quectel.constant.core.dept.DeptPersonMsgConstants;
import com.quectel.constant.core.workorder.WorkOrderConstants;
import com.quectel.constant.core.workorder.WorkOrderLogConstants;
import com.quectel.constant.global.SystemConstants;
import com.quectel.constant.global.annotation.RequirePermissions;
import com.quectel.constant.sys.SysCodeKeyConstants;
import com.quectel.core.module.dept.dto.DeptPersonDto;
import com.quectel.core.module.dept.service.DeptPersonService;
import com.quectel.core.module.mobileuser.service.MobileUserService;
import com.quectel.core.module.workorder.dto.WorkOrderDto;
import com.quectel.core.module.workorder.dto.WorkOrderLogDto;
import com.quectel.core.module.workorder.dto.WorkOrderServiceItemDto;
import com.quectel.core.module.workorder.service.WorkOrderLogService;
import com.quectel.core.module.workorder.service.WorkOrderService;
import com.quectel.core.module.workorder.service.WorkOrderServiceItemService;
import com.quectel.emp.constants.ResourceConstants;
import com.quectel.emp.controller.BaseController;
import com.quectel.emp.util.SessionHolder;
import com.quectel.emp.vo.workorder.HandleVo;
import com.quectel.emp.vo.workorder.WorkOrderStatisticsVo;
import com.quectel.sys.module.sys.service.SysUserService;
import com.quectel.util.common.*;
import com.quectel.util.ex.CheckErrorException;
import com.quectel.util.redis.RedisUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.concurrent.locks.Lock;
import java.util.stream.Collectors;

import static com.quectel.emp.constants.EmpRedisCacheConstants.PROJECT_NAME;

/**
 * @author caolu
 * @email louis.cao@quectel.com
 * @date 2021-10-19 13:06:54
 */
@RestController
@RequestMapping("workOrder")
@Tag(name = "WorkOrderController", description = "工单相关api")
public class WorkOrderController extends BaseController {
    private static final String WORK_ORDER_LOCK = PROJECT_NAME + "WORK_ORDER_LOCK:";
    @DubboReference
    private WorkOrderService workOrderService;
    @DubboReference
    private WorkOrderLogService workOrderLogService;
    @DubboReference
    private SysUserService sysUserService;
    @DubboReference
    private DeptPersonService deptPersonService;

    @Autowired
    private WorkOrderBusiness workOrderBusiness;
    @Autowired
    private DeptPersonMsgBusiness deptPersonMsgBusiness;
    @Autowired
    private CommonBusiness commonBusiness;
    @DubboReference
    private MobileUserService mobileUserService;
    @DubboReference
    private WorkOrderServiceItemService workOrderServiceItemService;
    /**
     * 查询状态
     */
    private static final String WORK_ORDER_INIT = "1";

    private static final Byte SUBMIT_STATUS_FLAG_HANDING = 1;
    private static final Byte SUBMIT_STATUS_FLAG_COMPLETE = 2;

    @GetMapping("todayStatistics")
    @Operation(summary = "首页-今日数据统计")
    @RequirePermissions(values = {ResourceConstants.WORK_ORDER_HANDLE})
    public Response<WorkOrderStatisticsVo> todayStatistics(
            @Parameter(description = "小区id") @RequestParam Long villageId) {
        Request request = Request.configParams(Request.parseParams(httpServletRequest));
        request.put(LambdaUtil.getFieldName(WorkOrderDto::getVillageId), villageId);
        request.put(SystemConstants.TIME_SLOT_KEY_PAIR.getLeft(), DateUtils.format(DateUtil.beginOfDay(new Date()), DateUtils.FormatType.COMMON));
        request.put(SystemConstants.TIME_SLOT_KEY_PAIR.getLeft(), DateUtils.format(DateUtil.endOfDay(new Date()), DateUtils.FormatType.COMMON));
        // 待接单
        request.put(LambdaUtil.getFieldName(WorkOrderDto::getStatus), WorkOrderConstants.ORDER_STATUS_INIT);
        int initTotal = workOrderService.queryTotal(request.getParams());

        // 已结单
        request.put(LambdaUtil.getFieldName(WorkOrderDto::getStatus), WorkOrderConstants.ORDER_STATUS_FINISHED);
        int finishedTotal = workOrderService.queryTotal(request.getParams());

        WorkOrderStatisticsVo vo = new WorkOrderStatisticsVo();
        vo.setInitTotal(initTotal);
        vo.setFinishedTotal(finishedTotal);
        return Response.<WorkOrderStatisticsVo>ok().wrap(vo);
    }


    /**
     * 列表
     */
    @GetMapping("mySubmitList")
    @Operation(summary = "查询我提交的工单列表，投诉建议和报事报修")
    @RequirePermissions(values = {ResourceConstants.WORK_ORDER_REPORT})
    public Response<Page<WorkOrderDto>> mySubmitList(
            @Parameter(description = "从1开始的页码数") @RequestParam Integer pageNo,
            @Parameter(description = "每页多少条") @RequestParam Integer pageSize,
            @Parameter(description = "2报事报修3投诉建议") @RequestParam Byte category,
            @Parameter(description = "1处理中2已完成 不传入为全部") @RequestParam(required = false) Byte statusFlag
    ) {


        //查询列表数据
        Request request = Request.configParams(Request.parseParams(httpServletRequest));

        request.getParams().put(LambdaUtil.getFieldName(WorkOrderDto::getOrderSource), WorkOrderConstants.ORDER_SOURCE_DEPT_PERSON.toString());
        request.getParams().put(LambdaUtil.getFieldName(WorkOrderDto::getSourceId), SessionHolder.getEmp().getId().toString());
        request.getParams().put(LambdaUtil.getFieldName(WorkOrderDto::getCategory), String.valueOf(category));
        if (SUBMIT_STATUS_FLAG_HANDING.equals(statusFlag)) {
            List<Byte> statuses = new ArrayList<>();
            statuses.add(WorkOrderConstants.ORDER_STATUS_INIT);
            statuses.add(WorkOrderConstants.ORDER_STATUS_HANDLING);
            statuses.add(WorkOrderConstants.ORDER_STATUS_FORWARD);
            request.getParams().put(SystemConstants.STATUSES, statuses);
        } else if (SUBMIT_STATUS_FLAG_COMPLETE.equals(statusFlag)) {
            List<Byte> statuses = new ArrayList<>();
            statuses.add(WorkOrderConstants.ORDER_STATUS_FINISHED);
            statuses.add(WorkOrderConstants.ORDER_STATUS_COMMENTED);
            request.getParams().put(SystemConstants.STATUSES, statuses);
        }


        int total = workOrderService.queryTotal(request.getParams());
        List<WorkOrderDto> list = null;
        if (total > 0) {
            list = workOrderService.queryList(request.getParams());
            for (WorkOrderDto workOrderDto : list) {
                DeptPersonDto deptPersonDto = deptPersonService.selectCacheById(workOrderDto.getHandlerId());
                if (deptPersonDto != null) {
                    workOrderDto.setHandlerUsername(deptPersonDto.getName());
                }
                workOrderDto.setStatusName(SysCodeUtils.easyToGetName(SysCodeKeyConstants.WORK_ORDER_STATUS, String.valueOf(workOrderDto.getStatus())));

            }
        } else {
            list = new ArrayList<>();
        }

        Page<WorkOrderDto> page = new Page<>(request.getPageNo(), request.getPageSize(), total, list);
        return Response.<Page<WorkOrderDto>>ok().wrap(page);
    }

    /**
     * 根据参数查询工单分页列表
     */
    @GetMapping("list")
    @Operation(summary = "根据参数查询工单分页列表")
    @RequirePermissions(values = {ResourceConstants.WORK_ORDER_HANDLE})
    public Response<Page<WorkOrderDto>> list(
            @Parameter(description = "从1开始的页码数") @RequestParam Integer pageNo,
            @Parameter(description = "每页多少条") @RequestParam Integer pageSize,
            @Parameter(description = "1待接单2进行中3已完成 不传查询全部（我参与过的）") @RequestParam(required = false) String statusFlag
    ) {

        //查询列表数据
        Request request = Request.configParams(Request.parseParams(httpServletRequest));

        //标记查询来源
        request.getParams().put("empQuery", SystemConstants.YES.toString());
        request.getParams().put("empQueryUserId", String.valueOf(SessionHolder.getEmp().getId()));
        request.getParams().put(LambdaUtil.getFieldName(WorkOrderDto::getVillageId), String.valueOf(SessionHolder.getEmp().getVillageId()));

        int total = workOrderService.queryTotal(request.getParams());
        List<WorkOrderDto> list = null;
        if (total > 0) {
            list = workOrderService.queryList(request.getParams());
            for (WorkOrderDto workOrderDto : list) {
                DeptPersonDto deptPersonDto = deptPersonService.selectCacheById(workOrderDto.getHandlerId());
                if (deptPersonDto != null) {
                    workOrderDto.setHandlerUsername(deptPersonDto.getName());
                }
                workOrderDto.setStatusName(SysCodeUtils.easyToGetName(SysCodeKeyConstants.WORK_ORDER_STATUS, String.valueOf(workOrderDto.getStatus())));
                if (WorkOrderConstants.ORDER_STATUS_FORWARD.equals(workOrderDto.getStatus())
                        && Objects.equals(workOrderDto.getHandlerId(), SessionHolder.getEmp().getId())) {
                    workOrderDto.setStatusName("处理中");
                }
            }
        } else {
            list = new ArrayList<>();
        }

        Page<WorkOrderDto> page = new Page<>(request.getPageNo(), request.getPageSize(), total, list);
        return Response.<Page<WorkOrderDto>>ok().wrap(page);
    }

    /**
     * 根据id查询工单记录
     */
    @GetMapping("info/{id}")
    @Operation(summary = "根据id查询工单记录")
    @RequirePermissions(values = {ResourceConstants.WORK_ORDER_HANDLE, ResourceConstants.WORK_ORDER_REPORT})
    public Response<WorkOrderDto> info(@PathVariable("id") Long id) {

        return Response.<WorkOrderDto>ok().wrap(workOrderBusiness.selectById(id));
    }


    /**
     * 保存
     */
    @PostMapping("submit")
    @Operation(summary = "提交报事报修，投诉建议和巡检相应的工单")
    @RequirePermissions(values = {ResourceConstants.WORK_ORDER_REPORT})
    public Response<Object> save(@RequestBody @Validated WorkOrderDto workOrderDto) {

        if (workOrderDto.getPictures() != null) {
            JacksonUtils.parseArray(workOrderDto.getPictures(), String.class);
        }
        if (workOrderDto.getCompletePictures() != null) {
            JacksonUtils.parseArray(workOrderDto.getCompletePictures(), String.class);
        }
        if (workOrderDto.getCommentPictures() != null) {
            JacksonUtils.parseArray(workOrderDto.getCommentPictures(), String.class);
        }

        Date nowDate = new Date();
        //填充基础数据
        workOrderDto.setCreateTime(nowDate);
        workOrderDto.setTenantId(SessionHolder.getEmp().getTenantId());
        workOrderDto.setVillageId(SessionHolder.getEmp().getVillageId());

        workOrderDto.setOrderSource(WorkOrderConstants.ORDER_SOURCE_DEPT_PERSON);
        workOrderDto.setSourceId(SessionHolder.getLoginEmpSession().getDeptPersonDto().getId());


        List<WorkOrderLogDto> logs = new ArrayList<>();
        WorkOrderLogDto initLog = new WorkOrderLogDto();
        // 处理人只有管理员和员工
        initLog.setHandlerType(WorkOrderConstants.ORDER_HANDLER_TYPE_DEPT_PERSON);
        initLog.setHandlerId(SessionHolder.getLoginEmpSession().getDeptPersonDto().getId());
        initLog.setOrderStatus(WorkOrderConstants.ORDER_STATUS_INIT);
        initLog.setOrderDes(
                WorkOrderLogConstants.INIT_LOG_DESC_FUNC.apply(Tuples.of(WorkOrderConstants.ORDER_SOURCE_DEPT_PERSON, SessionHolder.getEmp().getName()))
        );
        initLog.setCreateTime(nowDate);
        logs.add(initLog);


        if (WorkOrderConstants.ORDER_STATUS_FORWARD.equals(workOrderDto.getStatus())) {
            DeptPersonDto deptPersonDto = deptPersonService.selectById(workOrderDto.getHandlerId());
            if (deptPersonDto == null) {
                return Response.error("员工不存在");
            }
            WorkOrderLogDto forwordLog = new WorkOrderLogDto();
            forwordLog.setHandlerType(WorkOrderConstants.ORDER_HANDLER_TYPE_DEPT_PERSON);
            forwordLog.setHandlerId(workOrderDto.getHandlerId());
            forwordLog.setOrderStatus(WorkOrderConstants.ORDER_STATUS_FORWARD);
            forwordLog.setOrderDes(
                    WorkOrderLogConstants.FORWARD_LOG_DESC_FUNC.apply(Tuples.of(WorkOrderConstants.ORDER_HANDLER_TYPE_DEPT_PERSON, SessionHolder.getEmp().getName(), WorkOrderConstants.ORDER_HANDLER_TYPE_DEPT_PERSON, deptPersonDto.getName()))
            );
            forwordLog.setCreateTime(nowDate);
            logs.add(forwordLog);

            workOrderDto.setWorkOrderLogDtoList(logs);
            //直接指派第一次处理事件就是创建时间
            workOrderDto.setFirstHandTime(workOrderDto.getCreateTime());

            Long workOrderId = workOrderService.saveOrUpdateWorkOrderAndLog(workOrderDto);


            deptPersonMsgBusiness.pushMsg(
                    new ArrayList<>(Arrays.asList(deptPersonDto)),
                    DeptPersonMsgConstants.SourceType.WORK_ORDER_MSG,
                    workOrderId,
                    null,
                    "(指派提醒)" + commonBusiness.getAddressByVillageInfo(workOrderDto) + " " +
                            workOrderBusiness.getCategoryAndType(workOrderDto)[0] + "|" + workOrderBusiness.getCategoryAndType(workOrderDto)[1] + ",详情:" + workOrderDto.getDetail(),
                    true,
                    new PushConstants.PushType[]{PushConstants.PushType.WECHAT_OFFICIAL}
            );

        } else {
            workOrderDto.setStatus(WorkOrderConstants.ORDER_STATUS_INIT);
            workOrderDto.setHandlerId(null);
            workOrderDto.setWorkOrderLogDtoList(logs);
            workOrderService.saveOrUpdateWorkOrderAndLog(workOrderDto);
        }


        return Response.ok();
    }

    /**
     * 处理工单
     */
    @PostMapping("handle")
    @Operation(summary = "处理工单")
    @RequirePermissions(values = {ResourceConstants.WORK_ORDER_HANDLE})
    public Response<Object> handle(@RequestBody @Validated HandleVo handleVo) {

        if (handleVo.getCompletePictures() != null) {
            JacksonUtils.parseArray(handleVo.getCompletePictures(), String.class);
        }


        WorkOrderDto recVo = new WorkOrderDto();
        recVo.setId(handleVo.getId());
        recVo.setStatus(handleVo.getStatus());

        Date now = new Date();
        WorkOrderDto dbValue = workOrderService.selectById(handleVo.getId());
        Lock spinLock = RedisUtils.getSpinLock("WORK_ORDER_LOCK" + dbValue.getId());
        spinLock.lock();
        try {
            if (WorkOrderConstants.ORDER_STATUS_HANDLING.equals(handleVo.getStatus())) {
                if (!WorkOrderConstants.ORDER_STATUS_INIT.equals(dbValue.getStatus())) {
                    //只有初始化才可以接单
                    return Response.error("只有未分配的订单可以接单");
                }
                List<WorkOrderLogDto> logs = new ArrayList<>();
                WorkOrderLogDto log = new WorkOrderLogDto();
                log.setHandlerId(SessionHolder.getEmp().getId());
                log.setHandlerType(WorkOrderConstants.ORDER_HANDLER_TYPE_DEPT_PERSON);
                log.setOrderStatus(WorkOrderConstants.ORDER_STATUS_HANDLING);
                log.setOrderDes(WorkOrderLogConstants.HANDLING_LOG_DESC_FUNC.apply(Tuples.of(WorkOrderConstants.ORDER_HANDLER_TYPE_DEPT_PERSON, SessionHolder.getEmp().getName())));
                log.setCreateTime(now);
                logs.add(log);

                if (dbValue.getFirstHandTime() == null) {
                    //没有首次服务事件设置当前时间为首次接单时间
                    recVo.setFirstHandTime(now);
                }
                recVo.setHandlerId(SessionHolder.getLoginEmpSession().getDeptPersonDto().getId());
                recVo.setWorkOrderLogDtoList(logs);
                workOrderService.saveOrUpdateWorkOrderAndLog(recVo);


            } else if (WorkOrderConstants.ORDER_STATUS_FORWARD.equals(handleVo.getStatus())) {

                if (!WorkOrderConstants.ORDER_STATUS_HANDLING.equals(dbValue.getStatus())
                        && !WorkOrderConstants.ORDER_STATUS_FORWARD.equals(dbValue.getStatus())
                ) {
                    //只能指派已接单和已指派的
                    return Response.error("只能指派已接单的工单和别人指派给我的");
                }

                DeptPersonDto deptPersonDto = deptPersonService.selectCacheById(handleVo.getHandlerId());
                if (deptPersonDto == null) {
                    return Response.error("员工不存在");
                }
                List<WorkOrderLogDto> logs = new ArrayList<>();
                WorkOrderLogDto log = new WorkOrderLogDto();
                log.setHandlerType(WorkOrderConstants.ORDER_HANDLER_TYPE_DEPT_PERSON);
                log.setHandlerId(handleVo.getHandlerId());
                log.setOrderStatus(WorkOrderConstants.ORDER_STATUS_FORWARD);
                log.setOrderDes(
                        WorkOrderLogConstants.FORWARD_LOG_DESC_FUNC.apply(Tuples.of(WorkOrderConstants.ORDER_HANDLER_TYPE_DEPT_PERSON, SessionHolder.getEmp().getName(), WorkOrderConstants.ORDER_HANDLER_TYPE_DEPT_PERSON, deptPersonDto.getName()))
                );
                log.setCreateTime(now);
                logs.add(log);

                if (dbValue.getFirstHandTime() == null) {
                    //没有首次服务事件设置当前时间为首次接单时间
                    recVo.setFirstHandTime(now);
                }
                recVo.setHandlerId(handleVo.getHandlerId());
                recVo.setWorkOrderLogDtoList(logs);
                Long workOrderId = workOrderService.saveOrUpdateWorkOrderAndLog(recVo);

                deptPersonMsgBusiness.pushMsg(
                        new ArrayList<>(Arrays.asList(deptPersonDto)),
                        DeptPersonMsgConstants.SourceType.WORK_ORDER_MSG,
                        workOrderId,
                        null,
                        "(指派提醒)" + commonBusiness.getAddressByVillageInfo(dbValue) + " " +
                                workOrderBusiness.getCategoryAndType(dbValue)[0] + "|" + workOrderBusiness.getCategoryAndType(dbValue)[1] + ",详情:" + dbValue.getDetail(),
                        true,
                        new PushConstants.PushType[]{PushConstants.PushType.WECHAT_OFFICIAL}
                );

            } else if (WorkOrderConstants.ORDER_STATUS_FINISHED.equals(handleVo.getStatus())) {
                if (
                        WorkOrderConstants.ORDER_STATUS_FINISHED.equals(dbValue.getStatus())
                ) {
                    //已完成的不可以完成
                    return Response.error("已完成的工单无需重新完成");
                }
                if (!Objects.equals(dbValue.getHandlerId(), SessionHolder.getEmp().getId())) {
                    //只有自己可以处理自己的订单(该租户下的超管也是可以的)
                    return Response.error("只可以处理当前处理人为自己的工单");
                }
                List<WorkOrderLogDto> logs = new ArrayList<>();
                WorkOrderLogDto log = new WorkOrderLogDto();
                log.setHandlerId(SessionHolder.getEmp().getId());
                log.setHandlerType(WorkOrderConstants.ORDER_HANDLER_TYPE_DEPT_PERSON);
                log.setOrderStatus(WorkOrderConstants.ORDER_STATUS_FINISHED);
                if (StringUtils.isNotBlank(handleVo.getCompleteRemark())) {
                    log.setOrderDes("由员工:" + SessionHolder.getEmp().getName() + " 标记工单完成" + " 并备注:" + handleVo.getCompleteRemark());
                } else {
                    log.setOrderDes("由员工:" + SessionHolder.getEmp().getName() + " 标记工单完成");
                }
                log.setOrderDes(
                        WorkOrderLogConstants.FINISH_LOG_DESC_FUNC.apply(Tuples.of(WorkOrderConstants.ORDER_HANDLER_TYPE_DEPT_PERSON, SessionHolder.getEmp().getName(), handleVo.getCompleteRemark()))
                );

                log.setCreateTime(now);
                logs.add(log);

                if (dbValue.getFirstHandTime() == null) {
                    //没有首次服务事件设置当前时间为首次接单时间
                    recVo.setFirstHandTime(now);
                }
                // 完工单，服务项关系保存
                if (CollectionUtils.isNotEmpty(handleVo.getServiceItems())) {
                    List<WorkOrderServiceItemDto> serviceItems = handleVo.getServiceItems().parallelStream().map(o -> {
                        WorkOrderServiceItemDto workOrderServiceItemDto = workOrderServiceItemService.selectCacheById(o.getServiceItemId());
                        if (workOrderServiceItemDto != null) {
                            workOrderServiceItemDto.setAmount(o.getAmount());
                        }
                        return workOrderServiceItemDto;
                    }).filter(Objects::nonNull).collect(Collectors.toList());
                    recVo.setWorkOrderServiceItems(serviceItems);
                }
                recVo.setHandlerId(SessionHolder.getEmp().getId());
                recVo.setCompletePictures(handleVo.getCompletePictures());
                recVo.setCompleteRemark(handleVo.getCompleteRemark());
                recVo.setFinishTime(now);
                recVo.setWorkOrderLogDtoList(logs);
                workOrderService.saveOrUpdateWorkOrderAndLog(recVo);

                //推送给发起人
                if (WorkOrderConstants.ORDER_SOURCE_DEPT_PERSON.equals(dbValue.getOrderSource())) {
                    //暂时实现发起人是员工类型的
                    DeptPersonDto deptPersonDto = deptPersonService.selectById(dbValue.getSourceId());
                    if (deptPersonDto != null) {
                        deptPersonMsgBusiness.pushMsg(
                                new ArrayList<>(Arrays.asList(deptPersonDto)),
                                DeptPersonMsgConstants.SourceType.WORK_ORDER_MSG,
                                dbValue.getId(),
                                null,
                                "(完成提醒)" + commonBusiness.getAddressByVillageInfo(dbValue) + " " +
                                        workOrderBusiness.getCategoryAndType(dbValue)[0] + "|" + workOrderBusiness.getCategoryAndType(dbValue)[1] + ",详情:" + dbValue.getDetail(),
                                true,
                                new PushConstants.PushType[]{PushConstants.PushType.WECHAT_OFFICIAL}
                        );
                    }
                }


            }
            return Response.ok();
        } catch (Exception e) {
            throw new CheckErrorException(e);
        } finally {
            spinLock.unlock();
        }
    }

    /**
     * 评论工单
     */
    @PostMapping("comment")
    @Operation(summary = "评论工单")
    @RequirePermissions(values = {ResourceConstants.WORK_ORDER_REPORT})
    public Response<Object> comment(@RequestBody WorkOrderDto workOrderDto) {
        if (workOrderDto.getPictures() != null) {
            JacksonUtils.parseArray(workOrderDto.getPictures(), String.class);
        }
        if (workOrderDto.getCompletePictures() != null) {
            JacksonUtils.parseArray(workOrderDto.getCompletePictures(), String.class);
        }
        if (workOrderDto.getCommentPictures() != null) {
            JacksonUtils.parseArray(workOrderDto.getCommentPictures(), String.class);
        }
        WorkOrderDto dbValue = workOrderService.selectById(workOrderDto.getId());
        if (!WorkOrderConstants.ORDER_STATUS_FINISHED.equals(dbValue.getStatus())) {
            return Response.error("只能评价完成的工单");
        }
        if (!Objects.equals(dbValue.getOrderSource(), WorkOrderConstants.ORDER_SOURCE_DEPT_PERSON) &&
                !dbValue.getSourceId().equals(SessionHolder.getEmp().getId())) {
            //只能评价自己的
            return Response.error("非法的数据操作");
        }

        Date now = new Date();


        WorkOrderDto updateObj = new WorkOrderDto();
        updateObj.setId(workOrderDto.getId());
        updateObj.setScore(workOrderDto.getScore());
        updateObj.setAppraise(workOrderDto.getAppraise());
        updateObj.setCommentPictures(workOrderDto.getCommentPictures());
        updateObj.setStatus(WorkOrderConstants.ORDER_STATUS_COMMENTED);
        updateObj.setCommentTime(now);

        List<WorkOrderLogDto> logs = new ArrayList<>();
        WorkOrderLogDto log = new WorkOrderLogDto();
        log.setHandlerId(SessionHolder.getEmp().getId());
        log.setHandlerType(WorkOrderConstants.ORDER_HANDLER_TYPE_DEPT_PERSON);
        log.setOrderStatus(WorkOrderConstants.ORDER_STATUS_COMMENTED);
        log.setOrderDes(
                WorkOrderLogConstants.COMMENT_LOG_DESC_FUNC.apply(Tuples.of(WorkOrderConstants.ORDER_HANDLER_TYPE_DEPT_PERSON, SessionHolder.getEmp().getName(), workOrderDto.getAppraise()))
        );
        log.setCreateTime(now);
        logs.add(log);
        updateObj.setWorkOrderLogDtoList(logs);

        workOrderService.saveOrUpdateWorkOrderAndLog(updateObj);


        //推送最后处理的人（处理人完成后不发生变化，所以就是当前处理人）
        if (WorkOrderConstants.ORDER_SOURCE_DEPT_PERSON.equals(dbValue.getOrderSource())) {
            DeptPersonDto deptPersonDto = deptPersonService.selectById(dbValue.getHandlerId());
            if (deptPersonDto != null) {
                deptPersonMsgBusiness.pushMsg(
                        new ArrayList<>(Arrays.asList(deptPersonDto)),
                        DeptPersonMsgConstants.SourceType.WORK_ORDER_MSG,
                        dbValue.getId(),
                        null,
                        "(评价提醒)" + commonBusiness.getAddressByVillageInfo(dbValue) + "|" + workOrderBusiness.getCategoryAndType(dbValue)[0] + ":" + workOrderBusiness.getCategoryAndType(dbValue)[1] + "," + dbValue.getDetail(),
                        true,
                        new PushConstants.PushType[]{PushConstants.PushType.WECHAT_OFFICIAL}
                );
            }
        }

        return Response.ok();
    }


    /**
     * 查询服务人员列表
     */
    @GetMapping("getServiceUsers")
    @Operation(summary = "查询服务人员列表")
    public Response<List<DeptPersonDto>> getServiceUsers(@Parameter(description = "查询参数") @RequestParam(required = false) String queryText) {
        Map<String, Object> params = new HashMap<>();
        //限定为当前小区
        params.put(LambdaUtil.getFieldName(DeptPersonDto::getStatus), SystemConstants.YES);
        params.put(LambdaUtil.getFieldName(DeptPersonDto::getVillageId), String.valueOf(SessionHolder.getEmp().getVillageId()));
        params.put("queryText", queryText);
        List<DeptPersonDto> result = deptPersonService.queryList(params);
        result.forEach(v -> {
            v.setPassword(null);
        });
        return Response.<List<DeptPersonDto>>ok().wrap(result);
    }

}
